/**
 * Created by fengshenhai on 2017/7/19.
 */
$(function () {
    var socket = io();

    // $('form').submit(function(){
    //   socket.emit('chat message', $('#m').val());
    //   $('#m').val('');
    //   return false;
    // });
    // socket.on('chat message',function(msg){
    //    $('#messages').append($('<li>').text(msg));
    // });

    // socket.on('other user',function(msg){
    //   $('#messages').append($('<li>').text(msg));
    // })


    var $messages = $("#messages");
    var connected = false;
    var typing = false;
    var lastTypingTime;
    var FADE_TIME = 150; // ms
    var TYPING_TIMER_LENGTH = 400; // ms
    var COLORS = [
        '#e21400', '#91580f', '#f8a700', '#f78b00',
        '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
        '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
    ];
    //获取随机颜色
    var getUsernameColor =function(username) {
        // Compute hash code
        var hash = 7;
        for (var i = 0; i < username.length; i++) {
            hash = username.charCodeAt(i) + (hash << 5) - hash;
        }
        // Calculate color
        var index = Math.abs(hash % COLORS.length);
        return COLORS[index];
    }
    //判断是否是输入
    var updateTyping=function() {
        if (connected) {
            if (!typing) {
                typing = true;
                socket.emit('typing');
            }
            lastTypingTime = (new Date()).getTime();

            setTimeout(function () {
                var typingTimer = (new Date()).getTime();
                var timeDiff = typingTimer - lastTypingTime;
                if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
                    socket.emit('stop typing');
                    typing = false;
                }
            }, TYPING_TIMER_LENGTH);
        }
    }
    //打印信息
    var log = function (message, options) {
        var $el = $('<li>').addClass('log').text(message);
        addMessageElement($el, options);
    }
    //添加dom
    var addMessageElement = function (el, options) {
        var $el = $(el);

        // Setup default options
        if (!options) {
            options = {};
        }
        if (typeof options.fade === 'undefined') {
            options.fade = true;
        }
        if (typeof options.prepend === 'undefined') {
            options.prepend = false;
        }

        // Apply options
        if (options.fade) {
            $el.hide().fadeIn(FADE_TIME);
        }
        if (options.prepend) {
            $messages.prepend($el);
        } else {
            $messages.append($el);
        }
        $messages[0].scrollTop = $messages[0].scrollHeight;
    }
    //添加当前参与者信息
    var addParticipantsMessage = function (data) {
        var message = '';
        if (data.numUsers === 1) {
            message += "当前在线1人";
        } else {
            message += "当前在线" + data.numUsers + "人";
        }
        log(message);
    }

    var username;
    //防治注入标记信息
    var cleanInput = function (input) {
        return $('<div/>').text(input).text();
    }

    //向列表里增加聊天信息
    var addChatMessage = function (data,options) {
        var $usernameDiv = $('<span class="username"/>')
            .text(data.username)
            .css('color', getUsernameColor(data.username));
        var $messageBodyDiv = $('<span class="messageBody">')
            .text(data.message);
        var typingClass = data.typing ? 'typing' : '';
        var $messageDiv = $('<li class="message"/>')
            .data('username', data.username)
            .addClass(typingClass)
            .append($usernameDiv, $messageBodyDiv);

        addMessageElement($messageDiv, options);
    }
    //显示正在输入
    var addChatTyping=function(data) {
        data.typing = true;
        data.message = 'is typing';
        addChatMessage(data);
    }
    //获取正在输入提示的jquery对象
    var getTypingMessages=function(data) {
        return $('.typing.message').filter(function (i) {
            return $(this).data('username') === data.username;
        });
    }
    //移除正在输入的提示
    var removeChatTyping=function(data) {
        getTypingMessages(data).fadeOut(function () {
            $(this).remove();
        });
    }

    //发送信息
    var sendMessage = function () {
        var message = $("#inputMessage").val();
        message = cleanInput(message);
        $("#inputMessage").val("");
        //debugger;
        // 增加聊天信息到列表
        addChatMessage({
            username: username,
            message: message
        });
        //把消息发送給服务器
        socket.emit('new message', message);

    }
    //设置用户名称
    var setUsername = function () {
        username = cleanInput($("#inputName").val().trim());
        if (username) {
            $("#loginPage").fadeOut();
            $("#chatRoomPage").show();
            $("#inputMessage").focus();

            //把名字传給服务器
            socket.emit('add user', username);
        }
    }
    //键盘事件
    $(window).on('keydown', function (e) {
        if (event.which === 13) {
            if (username) {
                sendMessage();
                socket.emit('stop typing');
                typing = false;
            } else {
                setUsername();
            }
        }
    })

    //接受服务器广播信息
    socket.on('new message', function (data) {
        addChatMessage(data);
    })

    //用户登录
    socket.on('login', function (data) {
        connected = true;
        var message = "欢迎加入聊天室 ";
        log(message,{
            prepend:true
        });
        addParticipantsMessage(data);
    });

    //用户加入
    socket.on('user joined',function(data){
        log(data.username+' 加入');
        addParticipantsMessage(data);
    })

    //用户离开
    socket.on('user left', function (data) {
        log(data.username + ' 离开');
        addParticipantsMessage(data);
    });
    //用户输入
    $("#inputMessage").on("input",function(){
        updateTyping();
    })
    //用户停止输入
    socket.on('stop typing', function (data) {
        removeChatTyping(data);
    });
    //接收从服务端传来的用户正在输入
    socket.on('typing', function (data) {
        addChatTyping(data);
    });


});